<script setup>
import { onMounted, nextTick, ref, reactive, watch, toRefs, computed, onUnmounted } from 'vue'
import Config from '../mapInfoObj/mapConfig'
import { mapObj } from '../mapInfoObj/initMap'
import * as turf from '@turf/turf'
import Html2canvas from "html2canvas";
import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus'
import clearPng from '@/assets/img/toolbar/clear.png'
import measureAreaPng from '@/assets/img/toolbar/measureArea.png'
import measureDisPng from '@/assets/img/toolbar/measureDis.png'
import zoomoutPng from '@/assets/img/toolbar/zoomout.png'
import zoominPng from '@/assets/img/toolbar/zoomin.png'
import dingweiPng from '@/assets/img/toolbar/dingwei.png'
import screenshotPng from '@/assets/img/toolbar/screenshot.png'
import gifPng from '@/assets/img/toolbar/GIF.png'
import mian from '@/assets/img/mian.png'
import langxiang from '@/assets/img/langxiang.png'
import { resetLayer, addArrow, clearArrow } from '../mapInfoObj/initMap'
import mitt from '@/assets/js/mitt'

const urlGif = import.meta.env.VITE_backurl_gif
const props = defineProps({
  tools: {
    type: Array,
    default: [{
      // png: require("/img/toolbar/clear.png"),
      src: clearPng,
      id: "",
      label: "清除",
      // event: this.clear
    },
    // {
    //   // png: require("/img/toolbar/tagPng.png"),
    //   src: "/img/toolbar/tagPng.png",
    //   id: "",
    //   label: "标记",
    //   // event: this.tagPng
    // },
    {
      // png: require("/img/toolbar/measureArea.png"),
      src: measureAreaPng,
      id: "",
      label: "测面",
      // event: this.measureArea
    }, {
      // png: require("/img/toolbar/measureDis.png"),
      src: measureDisPng,
      id: "",
      label: "测距",
      // event: this.measureDis
    }, {
      // png: require("/img/toolbar/zoomout.png"),
      src: zoomoutPng,
      id: "",
      label: "缩小",
      // event: this.zoomOut
    }, {
      // png: require("/img/toolbar/zoomin.png"),
      src: zoominPng,
      id: "",
      label: "放大",
      // event: this.zoomIn
    }, {
      // png: require("/img/toolbar/dingwei.png"),
      src: dingweiPng,
      id: "",
      label: "定位",
      // event: this.locate
    }, {
      // png: require("../../assets/img/toolbar/screenshot.png"),
      src: screenshotPng,
      label: "快照",
      // event: this.screenShot,
      id: ""
    },
    //  {
    //   src: gifPng,
    //   id: "GIFShot",
    //   label: "动图",
    // },
      // {
      //   src: mian,
      //   id: "",
      //   label: "等值面",
      // },
      // {
      //   src: langxiang,
      //   id: "",
      //   label: "浪向",
      // }
    ],
  },
})
const { tools, mapEvent } = toRefs(props)

const emit = defineEmits(['handleMapEvent'])
onMounted(() => {
  // console.log('mapObj.map', mapObj.map);
  // allLayers = L.featureGroup().addTo(mapObj.map)

  mitt.on('closeArrow', () => {
    mapObj.map.off('zoomend', renderArrow)
  })
})
const handleBasicTool = (name) => {
  switch (name) {
    case '清除':
      clear()
      break;
    case '标记':
      tagPng()
      break;
    case '测面':
      measureArea()
      break;
    case '测距':
      measureDis()
      break;
    case '缩小':
      zoomOut()
      break;
    case '放大':
      zoomIn()
      break;
    case '定位':
      locate()
      break;
    case '快照':
      screenShot()
      break;
    case '动图':
      gifShot()
      break;
    case '等值面':
      (() => {
        if (!Config.curData?.wave && !Config.curData?.surge) {
          ElMessage.warning('未加载数据')
          return
        }
        if (mapObj.currentLine.length) {
          mapObj.currentLine.forEach(line => {
            Config.ToolLayers.removeLayer(line)
          })
          mapObj.currentLine = []
          return
        }
        breakDialog.value = true
      })()
      break;
    case '浪向':
      wavaArrow()
      break;
    default:
      break;
  }
}

// 按钮方法
const clear = () => {
  let allLayers = Config.ToolLayers
  allLayers.clearLayers()
}
// 测面的方法
const measureArea = () => {
  emit('handleMapEvent', 'close')

  mapObj.map.pm.enableDraw('Polygon', {
    snappable: true,
    snapDistance: 20,
    finishOn: 'dblclick',
    allowSelfIntersection: false,
    tooltips: true,
    templineStyle: {
      color: 'red',
      dashArray: '5, 5',
    },
    hintlineStyle: {
      color: 'red',
      dashArray: '5, 5',
    },
    pathOptions: {
      color: 'red',
      fillColor: 'red',
      fillOpacity: 0.4,
      opacity: 1,
      weight: 2,
      clickable: true,
    },
  })
  // 添加到Config.ToolLayers中
  mapObj.map.on('pm:create', (e) => {
    Config.ToolLayers.addLayer(e.layer)
    const polygonGeoJSON = e.layer.toGeoJSON();
    const area = turf.area(polygonGeoJSON);
    e.layer.bindPopup(`面积为：${(area / 1000000).toFixed(2)}平方千米`).openPopup();
    emit('handleMapEvent', 'open')
  })
}
// 测距的方法
const measureDis = () => {
  emit('handleMapEvent', 'close')
  mapObj.map.pm.enableDraw('Line', {
    snappable: true,
    snapDistance: 20,
    finishOn: 'dblclick',
    allowSelfIntersection: false,
    tooltips: true,
    templineStyle: {
      color: 'red',
      dashArray: '5, 5',
    },
    hintlineStyle: {
      color: 'red',
      dashArray: '5, 5',
    },
    pathOptions: {
      color: 'red',
      fillColor: 'red',
      fillOpacity: 0.4,
      opacity: 1,
      weight: 2,
      clickable: true,
    },
  })
  // 添加到Config.ToolLayers中
  mapObj.map.on('pm:create', (e) => {
    Config.ToolLayers.addLayer(e.layer)
    const lineGeoJSON = e.layer.toGeoJSON();
    const length = turf.length(lineGeoJSON);
    e.layer.bindPopup(`距离为：${(length / 1000).toFixed(2)}公里`).openPopup();
    emit('handleMapEvent', 'open')
  })
}
// 放大的方法
const zoomIn = () => {
  mapObj.map.zoomIn()
}
// 缩小的方法
const zoomOut = () => {
  mapObj.map.zoomOut()
}
// 全图的方法
const locate = () => {
  mapObj.map.setView(mapObj.center, mapObj.zoom)
  // 全国的中心点，请告诉我
}
// 快照的方法
const screenShot = () => {
  const screenshot = document.getElementById("mapContain");
  const opts = {
    logging: true,
    scale: 2,
    useCORS: true
  };
  Html2canvas(screenshot, opts).then(res => {
    const { height, width } = res;
    const base64 = res.toDataURL("image/png", 1);
    Render(base64, width, height, img => {
      Download(base64, "screenshot.png");
    });
  }, err => alert("截图失败，请重新尝试"))
},
  subGifShot = () => {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    // timeRange.value格式化为startDateTime和endDateTime，格式为2021-09-06 00:00

    // let allData = {
    //   startDateTime: timeRange.value[0],
    //   endDateTime: timeRange.value[1],
    //   timeDelay: timeDelay.value,
    //   gifDelay: gifDelay.value,
    //   urlHead: 'http://124.70.20.171:2009/wenzhou/#/chunde/surge/28.3,120.6993/8'
    // }
    let center = mapObj.map.getCenter().lat + ',' + mapObj.map.getCenter().lng
    let zoom = mapObj.map.getZoom().toString()

    let formData = new FormData()
    formData.append('startDateTime', timeRange.value[0])
    formData.append('endDateTime', timeRange.value[1])
    formData.append('timeDelay', timeDelay.value)
    formData.append('gifDelay', gifDelay.value)
    formData.append('urlHead', `http://192.168.1.205:8000/zdbzmbnw/#/chunde/${dataType.value}/${center}/${zoom}/`)
    //http://localhost:8000/web_0725/#/chunde/windLayer/28.3,120.6993/8/2023070600
    // console.log(`http://124.70.20.171:2009/wenzhou/#/chunde/${dataType.value}/${center}/${zoom}`);
    //   return
    axios({
      method: 'post',
      url: urlGif + '/buildGif',
      data: formData,
      responseType: 'blob',
      // withCredentials: false,
      // headers: {
      //   'Content-Type': 'application/json;charset=UTF-8'
      // }
    }).then(res => {
      console.log(res);
      if (res.status == 200) {
        loading.close()
        ElMessage.success('生成成功')
        gifDialog.value = false
        const a = document.createElement('a')
        a.href = URL.createObjectURL(res.data)
        a.download = 'screenshot.gif'
        a.click()
        // Download(urlGif + res.data.data, "screenshot.gif");
      } else {
        loading.close()
        ElMessage.error('生成失败')
      }
    })

  }

let currentLine = []
mapObj.currentLine = currentLine
// 绘制等值面
const isosurface = () => {
  breakDialog.value = false
  // return

  let { startLat, startLon, vscale, uscale } = Config.rasterHeader['global']
  let extent = [Config.rasterHeader.global.startLon, Config.rasterHeader.global.endLat, Config.rasterHeader.global.endLon, Config.rasterHeader.global.startLat]
  var cellWidth = 10;
  var pointGrid = turf.pointGrid(extent, cellWidth, { units: 'miles' });
  for (var i = 0; i < pointGrid.features.length; i++) {
    let row = Math.floor((startLat - pointGrid.features[i].geometry.coordinates[1]) / vscale)
    let col = Math.floor((pointGrid.features[i].geometry.coordinates[0] - startLon) / uscale)
    if (Config.curData?.wave) {
      pointGrid.features[i].properties.wavaValue = Config.curData?.wave[row][col].value
    } else if (Config.curData?.surge) {
      pointGrid.features[i].properties.wavaValue = Config.curData?.surge[row][col].value
    }
    // pointGrid.features[i].properties.wavaValue = Config.curData?.wave[row][col].value
  }
  // var breaks = [0, 0.5, 1, 1.5, 2, 2.5];
  // var breaks = [0, 5, 10, 15, 20, 25];
  let breaks = breaksRef.value.map(item => {
    return item.value
  })
  var lines = turf.isolines(pointGrid, breaks, { zProperty: 'wavaValue' });
  lines.features.forEach((lineType, linTypeIdx) => {
    lineType.geometry.coordinates.forEach((line, lineIdx) => {
      let latlngs = []
      line.forEach(point => {
        latlngs.push([point[1], point[0]])
      })

      // var linePh = turf.lineString(line);
      // var curved = turf.bezierSpline(linePh);
      // let latlngs = []
      // curved.geometry.coordinates.forEach(point => {
      //   latlngs.push([point[1], point[0]])
      // })
      // let color=Config.scalarColor.wave[linTypeIdx].color
      // let color = 'red'
      let color = breaksRef.value[linTypeIdx].color
      let lineC = L.polyline(latlngs, {
        color: color,
        weight: 1,
      }).addTo(Config.ToolLayers)
      mapObj.currentLine.push(lineC)
    })
  })

  resetLayer()
  // resetLayer()
}

// let isArrow = false
const wavaArrow = () => {
  // console.log(Config);
  if (!Config.curData?.wave) {
    ElMessage.warning('未加载海浪数据')
    return
  }
  // if (!Config.curData?.surge) {
  //   ElMessage.warning('未加载潮汐数据')
  //   return
  // }
  if (mapObj.allArrow.length > 0) {
    clearArrow()
    // isArrow = false
    mapObj.map.off('zoomend', renderArrow)
    return
  }


  renderArrow()
  // isArrow = true
  // 监听地图缩放
  mapObj.map.on('zoomend', renderArrow)
}

const renderArrow = () => {
  clearArrow()
  let step = Math.floor(100 / mapObj.map.getZoom()) * 5
  for (let row = 0; row < Config.curData?.wave.length; row = row + step) {
    for (let col = 0; col < Config.curData?.wave[row].length; col = col + step) {
      if (Config.curData?.wave[row][col] == -999) continue
      let data = {
        lat: Config.rasterHeader.global.startLat - row * Config.rasterHeader.global.vscale,
        lng: Config.rasterHeader.global.startLon + col * Config.rasterHeader.global.uscale,
        angle: Config.curData?.wave[row][col].angle,
      }
      addArrow(data)
    }
  }
  // resetLayer()
}

const gifDialog = ref(false),
  timeRange = ref(['2023-08-01 00:00', '2023-08-01 10:00']);
const gifShot = () => {
  gifDialog.value = true
}

const Render = (src, width, height, cb) => {
  const img = new Image();
  img.src = src;
  img.width = width;
  img.height = height;
  img.crossOrigin = "anonymous"; // 图像跨域时配置
  cb && cb(img);
},
  Download = (url, name) => {
    const target = document.createElement("a");
    target.href = url;
    target.download = name;
    const event = document.createEvent("MouseEvents");
    event.initEvent("click", true, true);
    target.dispatchEvent(event);
  }
const timeDelay = ref(1),
  gifDelay = ref(1),
  dataType = ref('waveLayer');

const timeDelayCom = computed({
  get() {
    return timeDelay.value + '小时'
  },
  set(val) {
    timeDelay.value = val
  }
})

const gifDelayCom = computed({
  get() {
    return gifDelay.value + '秒'
  },
  set(val) {
    gifDelay.value = val
  }
})

const breaksRef = ref([
  {
    color: '#00ff00',
    value: 0
  },
  {
    color: '#00ff00',
    value: 5
  },
  {
    color: '#00ff00',
    value: 10
  },
  {
    color: '#00ff00',
    value: 15
  },
  {
    color: '#00ff00',
    value: 20
  },
  {
    color: '#00ff00',
    value: 25
  },
]),
  breakDialog = ref(false)


const handleAdd = () => {
  breaks.value.push({
    color: '#00ff00',
    value: 0
  })
},
  handleDel = () => {
    breaks.value.pop()
  }

const allTypes = [
  {
    label: '海浪',
    value: 'waveLayer'
  },
  {
    label: '潮汐',
    value: 'tideLayer'
  },
  {
    label: '增水',
    value: 'surgeLayer'
  },
  {
    label: '海风',
    value: 'windLayer'
  }
]
onUnmounted(() => {
  mitt.off('closeArrow')
})
</script>

<template>
  <div class="MapBasicTool">
    <div class="item" v-for="(item, idx) in tools" @click="handleBasicTool(item.label)" :key="idx">
      <img :src="item.src" alt="">
      <span>{{ item.label }}</span>
    </div>
  </div>
  <el-dialog width="30%" v-model="gifDialog" :destroy-on-close="true" :show-close="false" top="30vh" title="GIF动图生成设置"
    :modal="true" :close-on-click-modal="false">
    <el-row>
      <el-col :span="24">
        <span class="gif_label">数据类型：</span>
        <!-- select -->
        <el-select v-model="dataType" class="m-2" placeholder="选择数据类型">
          <el-option v-for="item in allTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <span class="gif_label">时间范围：</span>
        <el-date-picker v-model="timeRange" type="datetimerange" range-separator="到" start-placeholder="开始时间"
          end-placeholder="结束时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" />
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <span class="gif_label">时间间隔：</span>
        <el-select v-model="timeDelayCom" class="m-2" placeholder="选择时间间隔">
          <el-option v-for="item in [1, 3]" :key="item" :label="item" :value="item" />
        </el-select>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <span class="gif_label">播放间隔：</span>
        <el-select v-model="gifDelayCom" class="m-2" placeholder="选择播放间隔">
          <el-option v-for="item in [1, 2, 3]" :key="item" :label="item" :value="item" />
        </el-select>
      </el-col>
    </el-row>

    <!-- foot -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="gifDialog = false">取消</el-button>
        <el-button type="primary" @click="subGifShot">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog width="30%" v-model="breakDialog" :destroy-on-close="true" :show-close="false" top="30vh" title="选择等值面断点"
    :modal="true" :close-on-click-modal="false">
    <!-- 默认填5个级别，也可以增加可删除级别 -->
    <el-row v-for="item in breaksRef" :gutter="20">
      <el-col :span="9">
        <el-color-picker v-model="item.color"></el-color-picker>
        {{ item.color }}
      </el-col>
      <el-col :span="9">
        <el-input v-model="item.value" placeholder=""></el-input>
      </el-col>
      <el-col :span="6">
        <el-button size="" @click="handleAdd">+</el-button>
        <el-button size="" @click="handleDel">-</el-button>

      </el-col>
    </el-row>


    <!-- foot -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="breakDialog = false">取消</el-button>
        <el-button type="primary" @click="isosurface">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang='less' scoped>
.el-row {
  margin-bottom: 10px;

  :deep(.el-date-editor) {
    max-width: 100% !important;
  }
}

.MapBasicTool {
  position: absolute;
  // top: 0;
  // left: 0;
  // top: 150px;
  bottom:30px;
  right: 5px;
  margin: 10px;
  padding: 5px;
  z-index: 499;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .3);
  border: 1px solid rgba(235, 235, 235, .38);
  background-color: var(--nv-bg-color);
  // width: 400px;
  height: 400px;
  // width: 60px;


  .item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 45px;
    height: 50px;
    font-size: 14px;
    cursor: pointer;

    img {
      width: 25px;
      height: 25px;
    }

    &:hover {
      transform: scale(1.1);
      color: var(--title-color);
    }
  }
}
</style>